# -*- coding: UTF-8 -*-
from typing import List
from leetcode_helper import TestcaseHelper, SolutionBase


class Solution(SolutionBase):
    # 解题的方法，命名和Leetcode的保持一致即可
    def trap_dp(self, height: List[int]) -> int:
        ans = 0
        count = len(height)
        left_max = [0] * count
        right_max = [0] * count
        left_max[0] = height[0]
        right_max[count - 1] = height[count - 1]

        for i in range(1, count):
            left_max[i] = max(left_max[i - 1], height[i])

        for i in range(count - 2, -1, -1):
            right_max[i] = max(right_max[i+1], height[i])

        for i in range(count):
            ans += min(left_max[i], right_max[i]) - height[i]

        return ans

    def trap(self, height: List[int]) -> int:
        ans = 0
        left_index = 0
        right_index = len(height) - 1
        left_max = right_max = 0

        while left_index < right_index:
            left_max = max(left_max, height[left_index])
            right_max = max(right_max, height[right_index])

            if left_max < right_max:
                ans += left_max - height[left_index]
                left_index += 1
            else:
                ans += right_max - height[right_index]
                right_index -= 1

        return ans


if __name__ == '__main__':
    solution = Solution()

    # 按照leetcode的题目说明，将基本的test case填入
    # 每条case的最后一个元素是正确的结果，即期待的结果
    # 使用元组来保存输入的数据，期待的结果
    testcases = [
        ([6, 4, 2, 0, 3, 2, 0, 3, 1, 4, 5, 3, 2, 7, 5, 3, 0, 1, 2, 1, 3, 4, 6, 8, 1, 3], 83),
        ([5, 4, 1, 2], 1),
        ([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1], 6),
        ([4, 2, 0, 3, 2, 5], 9)
    ]

    for case_item in testcases:
        # 获取测试用的case和期待的执行结果
        input1 = case_item[0]
        expect = case_item[len(case_item) - 1]

        exec_result = solution.trap(input1)

        # 判断执行结果，输出提示信息
        check_result = solution.check_result(expect, exec_result)
        TestcaseHelper.print_case(check_result, case_item, exec_result)

